package wangjg.test.lucene;

import java.io.File;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;

/**
 * This class is used to demonstrate the process of searching on an existing
 * Lucene index
 * 
 */
public class TxtFileSearcher {
	
	public static void main(String[] args) throws Exception {
		File indexDir = new File("E:\\temp\\index");
		FSDirectory directory = FSDirectory.open(indexDir);

		IndexReader reader = IndexReader.open(directory);
		IndexSearcher searcher = new IndexSearcher(reader);

		String keyword = "main";
		Term term = new Term("contents", keyword.toLowerCase());
		TermQuery query = new TermQuery(term);
		TopDocs topDocs = searcher.search(query, 100);

		System.out.println("检索到总数：" + topDocs.totalHits);
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;

		for (int i = 0; i < scoreDocs.length; i++) {
			ScoreDoc scoreDoc = scoreDocs[i];
			Document doc = searcher.doc(scoreDoc.doc);
			System.out.println("File: " + doc.get("path"));
		}
	}
}
